<?php
namespace lib;

class mysql {
	protected static $ins = null;
	protected $config = array();
	protected $conn = null; 
	final protected function __construct(){
		$this->config = conf::getIns();
		$spr = sprintf("%s:dbname=%s;host=%s",$this->config->ENGINE,$this->config->DB_NAME,$this->config->HOST);
		$this->conn = new \PDO($spr,$this->config->USER_NAME,$this->config->USER_PWD);
		$this->conn->query('set names utf8');
		return $this->conn;
	}
	
	final protected function __clone(){}
	
	public static function getIns(){
		if(!self::$ins instanceof self){
			self::$ins = new self;
		}
		return self::$ins;
	}
	
	public function query($sql){
		$pre = $this->conn->prepare($sql);
		if($pre){
			return $pre->execute();
		}else{
			return false;
		}
		
	}
	
	public function getAll($sql){
		$rs = $this->query($sql);
		return $rs->fetchAll();
	}
	
	public function getOne($sql){
		$rs = $this->query($sql);
		return $rs->fetch(PDO::FETCH_NUM)[0];
	}
	
	public function getRow($sql){
		$rs = $this->query($sql);
		return $rs->fetch(PDO::FETCH_ASSOC);
	}
	
	public function autoExec($table,$data,$act='insert',$where=0){
		if(!is_array($data)){
			return false;
		}
		if($act=='insert'){
			$sql = "insert into " . $table . " (" . implode(',',array_keys($data)) . ") values ('" . implode("','",array_values($data));
			$sql .= "')";
			return $this->query($sql);
		}else if($act == 'update'){
			$sql = "update " . $table . " set ";
			foreach($data as $k=>$v){
				$sql .= $k . '=\'' . $v . '\',';
			}
			$sql = rtrim($sql,',') . ' where ' . $where;
			return $this->query($sql);
		}
		
	}
	
	public function getLastId(){
		return $this->conn->lastInsertId();
	}
	
}
